package com.framework.res;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zul.Filedownload;

public class GeneradorXml {
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	public @interface FieldXml{
		String id();
	}
	
	
	public static void generarXmlFromBean(Object object, Class<?> classBean, String nameFile , Desktop desktop) throws Exception{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		DOMImplementation implementation = builder.getDOMImplementation();
		
		
		Document document = implementation.createDocument(null, "documento", null);
//		document.setXmlVersion("1.0");
		
		Element raiz = document.getDocumentElement();
		
		Field[] fields =  object.getClass().getDeclaredFields();
		for (Field field : fields) {
			    field.setAccessible(true);
			    FieldXml fieldXml = field.getAnnotation(FieldXml.class);
				if(fieldXml != null){
					 Object value = field.get(object);
					 Element nodoNombreCampo = document.createElement("fieldXml"); 
					 Attr  attr = document.createAttribute("id");
					 attr.setValue("" + fieldXml.id()); 
					 nodoNombreCampo.appendChild(attr); 	
					 
					 CDATASection cdataSection = document.createCDATASection("" + value);  
					 nodoNombreCampo.appendChild(cdataSection); 
					 raiz.appendChild(nodoNombreCampo);
				}
		}
		
		if(!nameFile.endsWith(".xml")){
			nameFile += ".xml";
		}
		
		Source source = new DOMSource(document);
		Result result = new StreamResult(new java.io.File(nameFile + "")); 
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.transform(source, result);
		
		
		java.io.InputStream is = desktop.getWebApp().getResourceAsStream(nameFile + "");
		if(is != null)
		Filedownload.save(is, "text/xml", nameFile + "");
	}
}
